//
//  TTCalculatorView.m
//  TaoTuo
//
//  Created by admin on 2020/2/4.
//  Copyright © 2020 admin. All rights reserved.
//

#import "TTCalculatorView.h"
#import "TTCalculatorCollectionView.h"
#import "TTCalculatorKeyboardView.h"
#import <IQKeyboardManager.h>
#import "TTDiamondCaculatorModel.h"

@interface TTCalculatorView ()<UITextFieldDelegate, TTCalculatorKeyboardViewDelegate>

@property (nonatomic, strong) TTCalculatorCollectionView *oneCollectionView;
@property (nonatomic, strong) TTCalculatorCollectionView *twoCollectionView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *roundBtn;       // 圆形
@property (nonatomic, strong) UIButton *differentBtn;   // 异形
@property (nonatomic, strong) UILabel *updateTimeLabel; //报价更新label
@property (nonatomic, strong) UITextField *zlTF;
@property (nonatomic, strong) UILabel *zlControlLabel;
@property (nonatomic, strong) UITextField *zkTF;
@property (nonatomic, strong) UITextField *hlTF;
@property (nonatomic, strong) UITextField *dollarTF;
@property (nonatomic, strong) UITextField *rmbTF;
@property (nonatomic, strong) UILabel *dollarCTLabel;
@property (nonatomic, strong) UILabel *rmbCTLabel;

@property (nonatomic, strong) TTCalculatorKeyboardView *keyboardView;
///裸石报价信息
@property (nonatomic, strong) NSMutableArray *diamondOfferArray;
///美元汇率
@property (nonatomic, copy) NSString *dollarRate;
/// 裸石形状
@property (nonatomic, copy) NSString *shape;
/// 裸石净度
@property (nonatomic, copy) NSString *clarity;
/// 裸石颜色
@property (nonatomic, copy) NSString *color;
/// 折扣前面的正负号
@property (nonatomic, copy) NSString *zkPrefix;


@property (nonatomic, strong) UITextField *currentEditTF;   //当前正在编辑的TF

@end

@implementation TTCalculatorView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.diamondOfferArray = [NSMutableArray array];
        self.shape = @"BR";
        [self getDiamondsQuotation];
        
        
    }
    return self;
}

/// 获取钻石国际报价
- (void)getDiamondsQuotation
{
    NSNumber *version = [[USER_DEFAULT objectForKey:@"Diamonds_version"] numberValue];
    version = version ? : @0;
    NSDictionary *dic = @{@"param.version" : version};
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getDiamondsQuotation_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSDictionary *dic = responseObject;
        self.dollarRate = [NSString stringWithFormat:@"%@", dic[@"DollarRate"]];
        [USER_DEFAULT setObject:dic[@"Version"] forKey:@"Diamonds_version"];
        
        [self.diamondOfferArray removeAllObjects];
        NSArray *list = dic[@"list"];
        if (list.count > 0) {
            [USER_DEFAULT setObject:list forKey:@"diamondList_key"];
            [USER_DEFAULT synchronize];
        } else {
            list = [USER_DEFAULT objectForKey:@"diamondList_key"];
        }
        
        for (NSDictionary *subDic in list) {
            TTDiamondCaculatorModel *model = [TTDiamondCaculatorModel modelWithJSON:subDic];
            [self.diamondOfferArray addObject:model];
        }
        
        [self setupSubviews];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self];
}

- (void)clickRoundBtn:(UIButton *)sender
{
    [self endEditing:YES];
    sender.selected = YES;
    sender.backgroundColor = kMainColor;
    sender.titleLabel.textColor = [UIColor whiteColor];
    _differentBtn.selected = NO;
    _differentBtn.backgroundColor = UIColorHex(F0F4F7);
    _differentBtn.titleLabel.textColor = UIColorHex(333333);
    
    self.shape = @"BR";
    
}

- (void)clickDifferentBtn:(UIButton *)sender
{
    [self endEditing:YES];
    sender.selected = YES;
    sender.backgroundColor = kMainColor;
    sender.titleLabel.textColor = [UIColor whiteColor];
    _roundBtn.selected = NO;
    _roundBtn.backgroundColor = UIColorHex(F0F4F7);
    _roundBtn.titleLabel.textColor = UIColorHex(333333);
    
    self.shape = @"PS";
    
}

#pragma mark - TTCalculatorKeyboardViewDelegate
- (void)calculatorKeyboardView:(TTCalculatorKeyboardView *)keyboardView selectString:(NSString *)selectString
{
    if (self.currentEditTF == nil) {
        return;
    }
    if ([selectString isEqualToString:@"."] && [self.currentEditTF.text containsString:@"."]) {
        return;
    }
    if (self.currentEditTF.text.length == 0 && [selectString isEqualToString:@"."]) {
        self.currentEditTF.text = @"0";
    }
    if (selectString.length == 0 && self.currentEditTF.text.length > 0) {
        self.currentEditTF.text = [self.currentEditTF.text substringToIndex:self.currentEditTF.text.length - 1];
    } else {
        self.currentEditTF.text = [NSString stringWithFormat:@"%@%@", self.currentEditTF.text, selectString];
    }
    
    if (self.currentEditTF == self.dollarTF && self.zlTF.text.floatValue > 0) {
        self.rmbTF.text = [NSString stringWithFormat:@"%.1f", self.dollarTF.text.floatValue * self.dollarRate.floatValue];
        CGFloat dollar = self.dollarTF.text.floatValue / self.zlTF.text.floatValue;
        CGFloat zk = dollar * 100 / self.zlControlLabel.text.intValue - 100;
        self.zkTF.text = [NSString stringWithFormat:@"%.1f", ABS(zk)];
        UIButton *zkBtn = (UIButton *)self.zkTF.leftView.subviews.firstObject;
        zkBtn.selected = zk > 0;
        self.dollarCTLabel.text = [NSString stringWithFormat:@"%.1f/Ct", dollar];
        self.rmbCTLabel.text = [NSString stringWithFormat:@"%.1f/Ct", self.rmbTF.text.floatValue / self.zlTF.text.floatValue];
        
    } else if (self.currentEditTF == self.rmbTF && self.zlTF.text.floatValue > 0) {
        self.dollarTF.text = [NSString stringWithFormat:@"%.1f", self.rmbTF.text.floatValue / self.dollarRate.floatValue];
        CGFloat dollar = self.dollarTF.text.floatValue / self.zlTF.text.floatValue;
        CGFloat zk = dollar * 100 / self.zlControlLabel.text.intValue - 100;
        self.zkTF.text = [NSString stringWithFormat:@"%.1f", ABS(zk)];
        UIButton *zkBtn = (UIButton *)self.zkTF.leftView.subviews.firstObject;
        zkBtn.selected = zk > 0;
        self.dollarCTLabel.text = [NSString stringWithFormat:@"%.1f/Ct", dollar];
        self.rmbCTLabel.text = [NSString stringWithFormat:@"%.1f/Ct", self.rmbTF.text.floatValue / self.zlTF.text.floatValue];
    }
}



- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    self.currentEditTF = textField;
    textField.layer.borderColor = kMainColor.CGColor;
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    textField.layer.borderColor = UIColorHex(C1C2C2).CGColor;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    textField.text = @"";
    if (textField == self.dollarTF) {
        self.rmbTF.text = @"0";
        self.zkTF.text = @"0";
    } else if (textField == self.rmbTF) {
        self.dollarTF.text = @"0";
        self.zkTF.text = @"0";
    }
    return YES;
}

- (void)zkBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.zkPrefix = sender.selected ? @"+" : @"-";
    
    if (self.zlControlLabel.text.intValue == 0 || self.dollarTF.text.floatValue == 0) {
        return;
    }
    NSString *zkValue = [NSString stringWithFormat:@"%@%@", self.zkPrefix, self.zkTF.text];
    CGFloat dollar = self.zlControlLabel.text.intValue * ((100 + zkValue.floatValue) / 100.0);
    self.dollarTF.text = [NSString stringWithFormat:@"%.1f", dollar];
    self.rmbTF.text = [NSString stringWithFormat:@"%.1f", dollar * self.dollarRate.floatValue];
            
}

- (void)didMoveToWindow
{
    [super didMoveToWindow];
    if (self.window) {
        [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = NO;
    } else {
        [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    }
}

- (void)setupSubviews
{
    CGRect oneRect = CGRectMake(0, 0, 50, self.height);
    NSArray *oneArray = @[@"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N"];
    @weakify(self)
    _oneCollectionView = [TTCalculatorCollectionView calculatorViewWithFrame:oneRect datas:oneArray selectedItemBlock:^(NSString * _Nullable title) {
        @strongify(self)
        [self endEditing:YES];
        self.currentEditTF = nil;
        self.color = title;
    }];
    [self addSubview:_oneCollectionView];
    
    CGRect twoRect = CGRectMake(51, 0, 50, self.height);
    NSArray *twoArray = @[@"IF", @"VVS1", @"VVS2", @"VS1", @"VS2", @"SI1", @"SI2", @"SI3", @"I1", @"I2", @"I3"];
    _twoCollectionView = [TTCalculatorCollectionView calculatorViewWithFrame:twoRect datas:twoArray selectedItemBlock:^(NSString * _Nullable title) {
        @strongify(self)
        [self endEditing:YES];
        self.currentEditTF = nil;
        self.clarity = title;
    }];
    [self addSubview:_twoCollectionView];
    
    CGFloat rightWidth = self.width - 125;
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(_twoCollectionView.right + 14, 0, rightWidth, self.height)];
    _scrollView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_scrollView];
    
    _roundBtn = [UIButton createButtonWithTitle:@"圆形" normalTitleColor:UIColorHex(333333) selectedTitleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:15] backgroundColor:kMainColor target:self action:@selector(clickRoundBtn:)];
    _roundBtn.frame = CGRectMake(0, 0, rightWidth * 0.5, 40);
    _roundBtn.selected = YES;
    [_scrollView addSubview:_roundBtn];
    
    _differentBtn = [UIButton createButtonWithTitle:@"异形" normalTitleColor:UIColorHex(333333) selectedTitleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:15] backgroundColor:UIColorHex(F0F4F7) target:self action:@selector(clickDifferentBtn:)];
    _differentBtn.frame = CGRectMake(_roundBtn.right, 0, rightWidth * 0.5, _roundBtn.height);
    [_scrollView addSubview:_differentBtn];
    
    UILabel *zlLabel = [UILabel labelWithTitle:@"重量(ct)" color:UIColorHex(333333) fontSize:13];
    [_scrollView addSubview:zlLabel];
    [zlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView);
        make.top.equalTo(self.roundBtn.mas_bottom).mas_offset(15);
    }];
    
    TTDiamondCaculatorModel *firstModel = self.diamondOfferArray.firstObject;
    NSString *title = [NSString stringWithFormat:@"国际报价%@更新", firstModel.UpdateTime];
    _updateTimeLabel = [UILabel labelWithTitle:title color:UIColorHex(CCCCCC) fontSize:10];
    [_scrollView addSubview:_updateTimeLabel];
    [_updateTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self).mas_offset(-10);
        make.bottom.equalTo(zlLabel);
    }];
    
    _zlTF = [self createTextField];
    [_scrollView addSubview:_zlTF];
    [_zlTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zlLabel);
        make.top.equalTo(zlLabel.mas_bottom).mas_offset(9.5);
        make.width.mas_equalTo(120);
        make.height.mas_equalTo(40);
    }];
    
    _zlControlLabel = [UILabel labelWithTitle:@"666666" color:UIColorHex(666666) fontSize:18];
    [_scrollView addSubview:_zlControlLabel];
    [_zlControlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zlTF.mas_right).mas_offset(10);
        make.top.bottom.equalTo(self.zlTF);
    }];
    
    UILabel *zkLabel = [UILabel labelWithTitle:@"折扣(%)" color:UIColorHex(333333) fontSize:13];
    [_scrollView addSubview:zkLabel];
    [zkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView);
        make.top.equalTo(self.zlTF.mas_bottom).mas_offset(15);
    }];
    
    UILabel *hlLabel = [UILabel labelWithTitle:@"汇率" color:UIColorHex(333333) fontSize:13];
    [_scrollView addSubview:hlLabel];
    [hlLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zlControlLabel);
        make.top.equalTo(zkLabel);
    }];
    
    UIView *zkLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 21, 15)];
    UIButton *zkBtn = [UIButton createButtonWithNormalImage:[UIImage imageNamed:@"-"] selectedImage:[UIImage imageNamed:@"+"] target:self action:@selector(zkBtnClick:)];
    zkBtn.frame = CGRectMake(6, 0, 15, 15);
    [zkLeftView addSubview:zkBtn];
    _zkTF = [self createTextField];
    _zkTF.leftView = zkLeftView;
    _zkTF.leftViewMode = UITextFieldViewModeAlways;
    [_scrollView addSubview:_zkTF];
    [_zkTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zlLabel);
        make.top.equalTo(zkLabel.mas_bottom).mas_offset(9.5);
        make.width.height.mas_equalTo(self.zlTF);
    }];
    
    _hlTF = [self createTextField];
    _hlTF.text = self.dollarRate;
    [_scrollView addSubview:_hlTF];
    [_hlTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zlControlLabel);
        make.top.equalTo(self.zkTF);
        make.width.height.mas_equalTo(self.zlTF);
    }];
    
    UILabel *dollarLabel = [UILabel labelWithTitle:@"美元($)" color:UIColorHex(333333) fontSize:13];
    [_scrollView addSubview:dollarLabel];
    [dollarLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView);
        make.top.equalTo(self.zkTF.mas_bottom).mas_offset(43);
    }];
    
    UILabel *rmbLabel = [UILabel labelWithTitle:@"人民币(￥)" color:UIColorHex(333333) fontSize:13];
    [_scrollView addSubview:rmbLabel];
    [rmbLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zlControlLabel);
        make.top.equalTo(dollarLabel);
    }];
    
    _dollarTF = [self createTextField];
    [_scrollView addSubview:_dollarTF];
    [_dollarTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zlLabel);
        make.top.equalTo(dollarLabel.mas_bottom).mas_offset(5);
        make.width.height.mas_equalTo(self.zlTF);
    }];
    
    _rmbTF = [self createTextField];
    [_scrollView addSubview:_rmbTF];
    [_rmbTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zlControlLabel);
        make.top.equalTo(self.dollarTF);
        make.width.height.mas_equalTo(self.zlTF);
    }];
    
    _dollarCTLabel = [UILabel labelWithTitle:@"0.0/Ct" color:UIColorHex(#666666) fontSize:12];
    [_scrollView addSubview:_dollarCTLabel];
    [_dollarCTLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zlLabel);
        make.top.equalTo(self.dollarTF.mas_bottom).mas_offset(20);
    }];
    
    _rmbCTLabel = [UILabel labelWithTitle:@"0.0/Ct" color:UIColorHex(#666666) fontSize:12];
    [_scrollView addSubview:_rmbCTLabel];
    [_rmbCTLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.zlControlLabel);
        make.top.equalTo(self.dollarCTLabel);
    }];
    
    [self layoutIfNeeded];
    _keyboardView = [TTCalculatorKeyboardView keyboardViewWithFrame:CGRectMake(0, self.dollarCTLabel.bottom + 45, rightWidth, rightWidth * 3/4 + 3)];
    _keyboardView.delegate = self;
    [_scrollView addSubview:_keyboardView];
    
    self.scrollView.contentSize = CGSizeMake(rightWidth, self.keyboardView.bottom + 30);
    self.zkPrefix = @"-";
    
    [[RACSignal combineLatest:@[RACObserve(self, shape), RACObserve(self, clarity), RACObserve(self, color), RACObserve(self.zlTF, text)] reduce:^id _Nonnull(NSString *shape, NSString *clarity, NSString *color, NSString *zlString){
        return @(shape.length > 0 && clarity.length > 0 && color.length > 0 && zlString.length > 0);
    }] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        if ([x boolValue]) {

            NSString *zl = self.zlTF.text;
            if (zl.floatValue >= 10) {
                zl = @"10";
            } else if (zl.floatValue >= 6 && zl.floatValue <= 9) {
                zl = @"5";
            }
            if ([zl hasSuffix:@"."]) {
                zl = [NSString stringWithFormat:@"%@0",zl];
            }
            if (zl.floatValue == 0) {
                return;
            }
            NSString *format = [NSString stringWithFormat:@"Shape=='%@' && Clarity=='%@' && Color=='%@' && DiaMinSize<=%@ && DiaMaxSize>=%@", self.shape, self.clarity, self.color, zl, zl];
            NSPredicate *predicate = [NSPredicate predicateWithFormat:format];
            NSArray *array = [self.diamondOfferArray filteredArrayUsingPredicate:predicate];
            
            TTDiamondCaculatorModel *model = array.firstObject;
            self.zlControlLabel.text = model.DiaPrice;
            
        } else {
            self.zlControlLabel.text = @"0";
        }
    }];
    
    [[RACSignal combineLatest:@[RACObserve(self.zlControlLabel, text), RACObserve(self.zkTF, text)] reduce:^id _Nonnull (NSString *price, NSString *zkValue){
        return @(price.intValue > 0);
    }] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        if ([self.dollarTF isFirstResponder] || [self.rmbTF isFirstResponder]) {
            return;
        }
        if ([x boolValue]) {
            NSString *zkValue = [NSString stringWithFormat:@"%@%@", self.zkPrefix, self.zkTF.text];
            CGFloat dollar = self.zlControlLabel.text.intValue * ((100 + zkValue.floatValue) / 100.0) * self.zlTF.text.floatValue;
            self.dollarTF.text = [NSString stringWithFormat:@"%.1f", dollar];
            self.rmbTF.text = [NSString stringWithFormat:@"%.1f", dollar * self.dollarRate.floatValue];
            self.dollarCTLabel.text = [NSString stringWithFormat:@"%.1f/Ct", dollar / self.zlTF.text.floatValue];
            self.rmbCTLabel.text = [NSString stringWithFormat:@"%.1f/Ct", dollar / self.zlTF.text.floatValue * self.dollarRate.floatValue];
        } else {
            self.dollarTF.text = @"0.0";
            self.rmbTF.text = @"0.0";
            self.dollarCTLabel.text = @"0.0/Ct";
            self.rmbCTLabel.text = @"0.0/Ct";
        }
    }];
    
    [RACObserve(self.hlTF, text) subscribeNext:^(NSString * _Nullable x) {
        @strongify(self)
        CGFloat rmb = self.dollarTF.text.floatValue * x.floatValue;
        self.rmbTF.text = [NSString stringWithFormat:@"%.1f", rmb];
    }];
    
}


- (UITextField *)createTextField
{
    UIView *inputView = [UIView new];
    UITextField *tf = [[UITextField alloc] init];
    tf.textColor = UIColorHex(333333);
    tf.font = [UIFont systemFontOfSize:17];
    tf.layer.borderColor = UIColorHex(C1C2C2).CGColor;
    tf.layer.borderWidth = 0.5;
    tf.backgroundColor = UIColorHex(F0F4F7);
    tf.textAlignment = NSTextAlignmentCenter;
    tf.delegate = self;
    tf.inputView = inputView;
    tf.inputAccessoryView = inputView;
    tf.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    return tf;
}



@end
